<script setup lang="ts">
import { ref, toRefs, computed, watch, } from 'vue'
import { updateUserBindAppReq } from '/@/api/approval'
import { GetAccessableAppByUserId } from '/@/api/managerAuthorize'
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();

const emit = defineEmits(['success', 'update:visible'])
const props = defineProps({
  appOptions: {
    type: Array,
    default: [],
  },
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: {},
  },
})
const loading = ref(false);

const modalActions = {
  close() {
    emit('update:visible', false)
  },
  async ok() {
    loading.value = true;
    const { respCode,respMsg } = await updateUserBindAppReq({
      userId: data.value.userId,
      clientIds: [...selectAppIds.value]
    })
    loading.value = false;
    if (respCode == 200) {
      createMessage({
        message: respMsg,
      })
      emit('success')
      modalActions.close()
    }
  }
}

const { appOptions, data, visible } = toRefs(props);
let selectAppIds: any = ref([]);

watch(visible, async (nv) => {
  if (nv) {
    const { data } = await GetAccessableAppByUserId({ userId: props.data.userId });
    selectAppIds.value = data.map(e => e?.clientId)
  } else {
    selectAppIds.value = [];
  }
})
let appOpts: any = ref([]);
appOpts = computed(() => appOptions.value?.map((e: any) => ({ label: e.clientName, value: e.id }) || []))


</script>

<template>
  <el-dialog v-model="visible" title="编辑授权应用" @close="modalActions.close" :width="750">
    <div style="padding: 40px">
      <el-row :gutter="20">
        <el-col :span="6" class="text-right mb-4">姓名:</el-col>
        <el-col :span="18">{{ data.username }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6" class="text-right mb-4">手机号:</el-col>
        <el-col :span="18">{{ data.mobile }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6" class="text-right mb-4">邮箱:</el-col>
        <el-col :span="18">{{ data.email }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6" class="text-right mb-4">授权应用:</el-col>
        <el-col :span="18">
          <el-select v-model="selectAppIds" multiple class="w-full">
            <el-option v-for="item in appOpts" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="modalActions.close">取消</el-button>
        <el-button type="primary" @click="modalActions.ok" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less">

</style>